package com.sinosoft.attachment;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;

@Controller
public class Fileupload extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Fileupload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置字符集
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		try {
			Attachment ach = new Attachment();
			ach.setCreateTime(new Date());
			// 容器相对路径
			String fpath = "/uploadFile/file";
			// 容器绝对路径
			String filepath = this.getServletContext().getRealPath(fpath);
			// 判断页面是否设置文件上次格式
			// boolean isMultipart =
			// ServletFileUpload.isMultipartContent(request);
			// 设置缓存路径 平判断是否存在
			File tmp = new File(fpath);
			if (!tmp.exists()) {
				tmp.mkdirs();
			}
			// 创建磁盘工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 文件缓存路径
			factory.setRepository(tmp);
			// 设置缓存大小
			factory.setSizeThreshold(10 * 1024);
			// 创建处理工具
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置客户端可接受最大文件 -1表示没有限制
			upload.setSizeMax(-1);
			// 解析得到所有的表单域，它们目前都被当作FileItem
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator ite = fileItems.iterator();
			FileItem item = null;
			String filename = null;
			while (ite.hasNext()) {
				// 循环读取每个表单
				item = (FileItem) ite.next();
				// 判断是否是文件表单
				if (!item.isFormField()) {
					filename = item.getName();
					 Long size=item.getSize();
					 double strcompany=1024*1024;
					
					 BigDecimal a = new BigDecimal((double)size/strcompany);
					 
					 // 文件不存在
					 File file=new File(filename);
					 if(!file.exists()){
						 
					 }
					 
					// 获取文件格式
					int pos = filename.lastIndexOf(".");
					Date date = new Date();
					String p = "/" + date.getTime() + filename.substring(pos);
					// 存放文件爱你路径
					filename = filepath + p;
					ach.setFilePath(filename);
					ach.setFileSize(a.setScale(5, 2));
					fpath = fpath + p;
					// 写入磁盘
					try {
						item.write(new File(filename));
					} catch (SizeLimitExceededException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						item.delete();
					}
				} else {

					String itemname = item.getFieldName();
					String itemvalue = item.getString();
					if (itemname.equals("filename")) {
						ach.setFileName(itemvalue);
					} else if (itemname.equals("filetype")) {
						ach.setFileType(Long.parseLong(itemvalue));
					} else if (itemname.equals("isrelease")) {
						ach.setIsRelease(Long.parseLong(itemvalue));
					}else if (itemname.equals("note")) {
						ach.setNote(itemvalue);
					}
				}
			}
			String path = "../attachment/fileUpload.html?filename="
					+ ach.getFileName() + "&filetype=" + ach.getFileType()
					+ "&filepath=" + fpath + "&isrelease=" + ach.getIsRelease()+"&filesize="+ach.getFileSize()+"&note="+ach.getNote();
			response.sendRedirect(path);

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
